/*
 * @Description: 上传excel hook
 * @Author: xjc
 * @Date: 2022-06-17 11:10:05
 * @LastEditTime: 2022-06-20 09:35:58
 * @LastEditors: 徐建辰
 */
import {ref} from 'vue'
import {ElMessage} from 'element-plus'
import {read, utils} from 'xlsx'
import {isExcel, getHeaderRow} from '@/utils/excel'

export default function useUploadExcel(props) {
  /* data */
  const excelUploadRef = ref(null)
  const loading = ref(false)
  const excelData = ref({
    header: null,
    results: null
  })

  // 生成数据
  function generateData({header, results}) {
    const p = props
    excelData.value = {header, results}
    p.onSuccess && p.onSuccess(excelData.value)
  }
  // 拖拽事件
  function handleDrop(e) {
    e.stopPropagation()
    e.preventDefault()
    if (loading.value) return
    const files = e.dataTransfer.files
    if (files.length !== 1) {
      ElMessage.error('Only support uploading one file!')
      return
    }
    const rawFile = files[0] // only use files[0]
    if (!isExcel(rawFile)) {
      ElMessage.error('Only supports upload .xlsx, .xls, .csv suffix files')
      return false
    }
    upload(rawFile)
    e.stopPropagation()
    e.preventDefault()
  }
  function handleDragover(e) {
    e.stopPropagation()
    e.preventDefault()
    e.dataTransfer.dropEffect = 'copy'
  }
  function handleUpload() {
    excelUploadRef.value.click()
  }
  function handleClick(e) {
    const files = e.target.files
    const rawFile = files[0] // only use files[0]
    if (!rawFile) return
    upload(rawFile)
  }
  function upload(rawFile) {
    excelUploadRef.value.value = null // fix can't select the same excel
    const p = props
    if (!p.beforeUpload) {
      readerData(rawFile)
      return
    }
    const before = p.beforeUpload(rawFile)
    before && readerData(rawFile)
  }
  // 读取数据
  function readerData(rawFile) {
    loading.value = true
    return new Promise(resolve => {
      const reader = new FileReader()
      reader.onload = e => {
        const data = e.target.result
        const workbook = read(data, {type: 'array'})
        const firstSheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[firstSheetName]
        const header = getHeaderRow(worksheet)
        const results = utils.sheet_to_json(worksheet)
        generateData({header, results})
        loading.value = false
        resolve()
      }
      reader.readAsArrayBuffer(rawFile)
    })
  }

  return {
    excelUploadRef, loading, excelData,
    handleClick, handleDragover, handleUpload, handleDrop, generateData
  }
}